//
//  RoomSettingVC.m
//  YouinRTCDemo
//
//  Created by 潘欣 on 2024/6/16.
//

#import "RoomSettingVC.h"
#import "SettingTableViewCell.h"
#import "RYAlertController.h"
#import "AppDelegate.h"
#import "LandscapeViewController.h"
#import "AFNetworking.h"
#import "AccountViewController.h"
@interface RoomSettingVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSMutableArray *valueArray;

@property (nonatomic,strong)NSString *enterpriseId;
@end

@implementation RoomSettingVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}
- (void)goBackToPreview
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"设置";
    UIButton *buttonBack=[UIButton buttonWithType:UIButtonTypeCustom];
    buttonBack.frame =  CGRectMake(0, 0, 50, 50);
    [buttonBack setImage:[UIImage imageNamed:@"nav-return"] forState:UIControlStateNormal];
    [buttonBack addTarget:self action:@selector(goBackToPreview) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:buttonBack];
    buttonBack.imageEdgeInsets = UIEdgeInsetsMake(0, -27, 0, 0);
    self.navigationItem.leftBarButtonItem = backItem;
    
    NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];

    self.dataArray = [[NSMutableArray alloc] initWithObjects:@"横屏开播",@"账号",@"版本号", nil];
    self.valueArray = [[NSMutableArray alloc] initWithObjects:@"开直播     ",@"",appVersion, nil];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorColor = RYColorForHex(@"#f5f6fa");
    self.tableView.showsVerticalScrollIndicator = false;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[SettingTableViewCell class] forCellReuseIdentifier:@"TableViewCell"];
    self.tableView.backgroundColor = RYColorForHex(@"#f5f6fa");
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        
    }
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(YPW_kStatusBarHeight+kNavBarHeight);
    }];
    
    [self getEnterPriseId];
}


- (void)getEnterPriseId
{
    
    
    NSDictionary *dict =  [[YouinRTCManager shardManager] readNSUserDefaults];
    NSDictionary *dic = @{@"authorization":[NSString stringWithFormat:@"JWT %@",dict[@"token"]]};

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    NSString *urlString = [NSString stringWithFormat:@"%@v1/enterprise/enterprise_info/",HTTPSURL];
    __weak typeof(self) weakSelf = self;

    [manager GET:urlString parameters:nil headers:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject[@"code"] intValue] == 200)
        {
            weakSelf.enterpriseId = responseObject[@"result"][@"enterprise_id"];
        }else{
            [[ZXMessageCase shareInstace] showMessage:responseObject[@"msg"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark - numberOfRowsInSection
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    static NSString *FormCheckCellID = @"TableViewCell";
    SettingTableViewCell *cell = (SettingTableViewCell *)[tableView dequeueReusableCellWithIdentifier:FormCheckCellID];
    if (cell == nil) {
        cell = [[SettingTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:FormCheckCellID];
    }
    cell.titleLabel.text = self.dataArray[indexPath.row];
    cell.traingLabel.text = self.valueArray[indexPath.row];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    if (indexPath.row == 0 || indexPath.row == 1) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        LandscapeViewController *LandscapeVC = [[LandscapeViewController alloc] init];
        [self.navigationController pushViewController:LandscapeVC animated:YES];

    }
    if (indexPath.row == 1) {
        AccountViewController *accountVC = [[AccountViewController alloc] init];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSDictionary *userInfo = [defaults dictionaryForKey:@"userInfo"];
        accountVC.phone = userInfo[@"username"];
        accountVC.enterpriseId = self.enterpriseId;
        [self.navigationController pushViewController:accountVC animated:YES];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = RYColorForHex(@"#f5f6fa");
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"退出登录" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor whiteColor];
    btn.frame = CGRectMake(0, 0, SCREEN_WIDTH, 44);
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn addTarget:self action:@selector(logOut) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 64.0;
}

- (void)logOut
{
    [RYAlertController showAlertWithTitle:@"确定要退出登录么？" message:@"" appearanceProcess:^(RYAlertController * _Nonnull alertMaker) {
        alertMaker.addActionDefaultTitle(@"取消").addActionDestructiveTitle(@"确定");
    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, RYAlertController * _Nonnull alertSelf) {
        // 1.2.用户确定后跳转登录页面
        if (buttonIndex == 1) {
            
            [[YouinRTCManager shardManager] removeToken];
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            NSDictionary *userInfo = [defaults dictionaryForKey:@"userInfo"];
            NSDictionary *dict = @{@"username": userInfo[@"username"], @"password": userInfo[@"password"],@"exprise_time":@"",@"token":@""};
            
            [defaults setObject:dict forKey:@"userInfo"];
            [defaults synchronize];
            
            /**退出登录*/
            [(AppDelegate *)[UIApplication sharedApplication].delegate loginOutWindowHome];
        }
    }];
}


@end
